//
//  ZLEmotionCell.swift
//  表情键盘
//
//  Created by zhanglongtao on 17/1/13.
//  Copyright © 2017年 hanju001. All rights reserved.
//

import UIKit

@objc protocol ZLEmotionCellDlegate: NSObjectProtocol{
    
    func emotionCellDidSelectedEmotion(cell: ZLEmotionCell, em: ZLEmotion?)
    
}

// 表情的页面cell 每一个页面显示20个表情
//每一个cell就是和collectionView一样大小
//每一个cell中用九宫格的算法，自动添加20个表情
// 最后一个位置放置一个删除按钮
class ZLEmotionCell: UICollectionViewCell {
    
    //代理
    weak var delegate: ZLEmotionCellDlegate?
    
    
    var emotions: [ZLEmotion]? {
        
        didSet{
            print("表情包的数量\(emotions?.count)")
            for v in contentView.subviews {
                
                v.isHidden = true
            }
            //显示删除按钮
            contentView.subviews.last?.isHidden = false
            //遍历数组设置按钮图像
            for (i, em) in (emotions ?? []).enumerated() {
                
                if let btn = contentView.subviews[i] as? UIButton {
                    
                    
                    btn.setImage(em.image, for: [])
                    //设置emoji的字符串  这样写自带清空功能
                    
                    btn.setTitle(em.emoji, for: [])
                    
                    btn.isHidden = false
                }
            }
        }
    }
    
    //表情选择提示视图
    private lazy var tapView = ZLEmotionTapView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func awakeFromNib() {
        
        
        setupUI()
    }
    // MARK: -- 监听方法
    @objc fileprivate func selectedEmotionButton(button: UIButton){
        
        //取tag
        let tag = button.tag
        //根据tag
        var em: ZLEmotion?
        if tag < (emotions?.count)!{
            
            em = emotions?[tag]
        }
        //通知代理工作
        delegate?.emotionCellDidSelectedEmotion(cell: self, em: em)
        //print(em)
    }
    
    override func willMove(toWindow newWindow: UIWindow?) {
        super.willMove(toWindow: newWindow)
        
        guard let w = newWindow else {
            
            return
        }
        
        tapView.isHidden = true
        //将提示视图添加到窗口上
        w.addSubview(tapView)
        
    }
    
    //长按手势识别 添加提示视图
    @objc fileprivate func longGesture(gesture: UILongPressGestureRecognizer) {
        
        let location = gesture.location(in: self)
        
        guard let button = buttonWithLocation(location: location) else{
            
            tapView.isHidden = true
            return
        }
        //处理手势
        //在处理手势的时候，不要试图一些吧所欲的状态都处理完毕
        switch gesture.state {
        case .began, .changed:
            tapView.isHidden = false
            
            //坐标系的转换
            let center = self.convert(button.center, to: window)
            tapView.center = center
            //设置提示视图的表情模型
            if button.tag < emotions?.count ?? 0 {
                
                tapView.emotion = emotions?[button.tag]
            }
        case .ended:
            tapView.isHidden = true
            //执行选中按钮
            selectedEmotionButton(button: button)
            
        case .cancelled, .failed:
            tapView.isHidden = true
        default:
            break
        }
        
    }
    //获取触摸位置对应的按钮
    private func buttonWithLocation(location: CGPoint) -> UIButton?{
        
        //遍历所有的子视图  如果子视图可见  同时location  确认是按钮
        for btn in contentView.subviews as! [UIButton]{
            if btn.frame.contains(location) && !btn.isHidden && btn != contentView.subviews.last {
                
                return btn
            }
        }
        
        return nil
    }
}

private extension ZLEmotionCell {
    
    //从xib加载bounds中xib中定义的大小
    //纯代码开发就是布局属性中设置的大小
    func setupUI() {
    
        //连续创建21个按钮
        
        let rowCount = 3;
        let colCount = 7
        
        let leftMargin: CGFloat = 8
        //为分页控件预留
        let bottomMargin: CGFloat = 16
        let w = (bounds.width - 2 * leftMargin) / CGFloat(colCount)
        let h = (bounds.height - bottomMargin) / CGFloat(rowCount)
        
        for i in 0..<21 {
            
            let row = i / colCount;
            let col = i % colCount;
            let btn = UIButton()
            //设置大小
            let x = leftMargin + CGFloat(col) * w
            let y = CGFloat(row) * h
            btn.frame = CGRect(x: x, y: y, width: w, height: h)
            //设置字体大小
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 32)
            //设置按钮tag
            btn.tag = i
            
            btn.addTarget(self, action: #selector(selectedEmotionButton(button:)), for: .touchUpInside)
            contentView.addSubview(btn)
        }
        //取出末尾的删除按钮
        let removeBtn = contentView.subviews.last as? UIButton
        let image = UIImage(named: "compose_emotion_delete_highlighted", in: EmotionManager.shared.bundle, compatibleWith: nil)
        removeBtn?.setImage(image, for: [])
        //添加长按手势
        let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longGesture))
        longPress.minimumPressDuration = 0.1
        addGestureRecognizer(longPress)
        
    }
}
